import { persist } from "zustand/middleware";
import { bannerGet, IBannerType } from "@/api/home";
import create from "zustand";
interface BannerState {
  banner: Array<IBannerType>;
  fetchBanner: () => void;
  addBanner: (obj: IBannerType) => void;
}
export const useBanner = create<BannerState>()(
  persist(
    (set, get) => ({
      banner: [],
      //带有异步请求方法
      fetchBanner: async () => {
        let res = await bannerGet();
        return set({ banner: res.data.results });
      },
      addBanner: (obj) => {
        let arr = get().banner; //获取状态机原来的数据包
        arr.push(obj);
        return set({
          banner: arr,
        });
      },
    }),
    {
      name: "banner-list",
      getStorage: () => sessionStorage, //可选配置，指定存储位置，默认存在localStorage中
    }
  )
);

// 添加持久化能力前
// export const useBanner = create<BannerState>((set, get) => ({}));

// 添加持久化能力后
// export const useBanner = create<BannerState>()(persist(
//   (set, get) => ({}),  //原来的状态机方法
//   {   //本地存储配置
//     name:'banner-list' //本地存储的数据包名称
//   }
// ));
